package com.ccteam.fluidmusic.ui.search

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ccteam.fluidmusic.repositories.search.CurrentSearchRepository
import com.ccteam.fluidmusic.utils.setValueIfNew
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/16
 *
 * 首页搜索总ViewModel，用于管控搜索内容显示
 */
@HiltViewModel
class HomeSearchViewModel @Inject constructor(
    private val currentSearchRepository: CurrentSearchRepository
): ViewModel() {

    /**
     * 是否应该显示搜索结果
     * 当按下enter搜索时为 true，其余时间为false
     */
    private val _shouldShowResult = MutableLiveData(false)
    val shouldShowResult: LiveData<Boolean> get() = _shouldShowResult

    /**
     * 当前检索的内容文本
     */
    private val _searchKey = MutableLiveData<String>()
    val searchKey: LiveData<String> get() = _searchKey

    /**
     * 最近搜索列表
     */
    private val _currentSearchList = MutableLiveData<List<String>>()
    val currentSearchList: LiveData<List<String>> get() = _currentSearchList

    private var currentSearchDataJob: Job? = null
    init {
        currentSearchDataJob = viewModelScope.launch {
            currentSearchRepository.getCurrentContent().collectLatest {
                _currentSearchList.value = it.searchKeyList.reversed()
            }
        }
    }

    fun showResult(showResult: Boolean){
        _shouldShowResult.setValueIfNew(showResult)
    }

    fun setNewSearchKey(searchKey: String){
        _searchKey.value = searchKey
    }

    fun editCurrentSearchContent(){
        viewModelScope.launch {
            _searchKey.value?.let {
                currentSearchRepository.editCurrentContent(it)
            }
        }
    }
}